var express = require('express');
var router = express.Router();
var request = require('request');

var CommonJS = require('../../../common/common');
var DBConfig = require('../../../db/dbconfig');
var mysql = require('mysql');
var pool = mysql.createPool(DBConfig.mysql2);


// 获取商品 一级分类的商品
router.get('/jkyx/goods_list', function(req, res, next) {
	var param = req.query || req.params; 
	var classify_id = param.classify_id || '';
	var classify_name = param.classify_name || '';
	if (classify_id == '') {
		res.end(JSON.stringify({
 			msg: '请传入分类id',
 			status:'105',
 		}));
 		return;
	}
    pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}
		connection.query(DBConfig.getGoodsByClassify,[classify_id,classify_id,classify_id,classify_id],function (err, results) {
			connection.release();
			if (err){
			  	res.end(JSON.stringify({
	     			msg: '数据库查询失败',
	     			status:'102',
	     			err: err
	     		}));
			}else{
				// 处理商品分类
				var subClassifyItems = results[0];
				var classifyItem = {
					id: classify_id,
					name: classify_name
				}
				var subClassify = [];
				subClassify.push(classifyItem);
				subClassify = subClassify.concat(subClassifyItems);
				if (classify_name == '') {
					subClassify = [];
				}
				// 处理商品 和 规格
				var goods = results[1];
				var goods_len = goods.length;
				var specs = results[2];
				var spec_len = specs.length;
				for (var i = 0; i < goods_len; i ++) {
					var salecount = 0;
					var spec = [];
					for (var j = 0; j < spec_len; j ++) {
						if (specs[j].goods_id == goods[i].id) {
							salecount = salecount + specs[j].salecount;
							spec.push({
								id: specs[j].id,
								salecount: specs[j].salecount,
								price: specs[j].price / 100,
								spec: specs[j].spec,
								origprice: specs[j].origprice,
								erpcode: specs[j].erpcode,
								stock: specs[j].stock,
							})
						}
					}
					goods[i].salecount = salecount;
					goods[i].spec = spec;
					goods[i].imgs = JSON.parse(goods[i].imgs);
				}
				res.end(JSON.stringify({
	     			msg: '操作成功',
	     			status:'100',
	     			classify: subClassify,
	     			goods: goods
	     		}));	         
			}
		})
	})
});


module.exports = router;
